package com.chookss.home.document;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.StaticClass;
import com.chookss.base.X5WebView;
import com.chookss.home.entity.DocunmentEntity;
import com.chookss.home.studyPlan.StudyPlanAddActivity;
import com.chookss.tools.AESEncrypt;
import com.chookss.tools.FileUtilss;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.NavigationTools;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.OkGoUtil;
import com.chookss.tools.okgoconfig.callback.JsonCallback;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.chookss.tools.old.Base64Utils;
import com.chookss.view.BottomListsDialog;
import com.chookss.view.ForScreenInitDialog;
import com.chookss.view.ProgressBarView;
import com.chookss.view.SelectDialogListener;
import com.chookss.view.listener.ShareDialogListener;
import com.chookss.wxapi.ShareActivity;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.johnrambo.ktea.ktExtends.ShareUtils;
import com.lvgroup.hospital.base.BaseAct;
import com.lzy.okgo.model.Response;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.tbs.reader.ITbsReader;
import com.tencent.tbs.reader.ITbsReaderCallback;
import com.tencent.tbs.reader.TbsFileInterfaceImpl;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class DocumentPreviewActivity extends BaseAct {
    private FrameLayout pdf_rl;
    private RelativeLayout title;
    private TextView tvTiltle, tvComplete, tvCompleteNum;
    private ImageView iv_DataBaseBack, ivCollect;
    private LinearLayout common_right_iv_ll, common_collect_ll;
    private RelativeLayout rlCircle;
    private ProgressBarView progress_bar;
    private X5WebView webView;
    //    private String fileName, dataCode, fileAllUrl;
    private String dataCode;
    private String fileAllUrl;
    private String fileName;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private int timeEnd = -1;//-1观看不到60s  0观看了60s  1已经调用学习任务接口
    private String compeleteFlag = "";
    private DocunmentEntity docunmentEntity;
    private String lpFlag = "";//0禁止1正常
    private List<String> dialogList = new ArrayList<>();
    private BottomListsDialog bottomListsDialog = null;
    private boolean openFile = true;
    private boolean isCollect = false;//是否收藏
    private boolean secret = false;//是否私密  私密不得收藏不得分享
    private boolean isDestroyed = false;
    private boolean openStatus=false;//是否正常打开文档

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_document_preview);
        lpFlag = new ShareUtils().getString(this, StaticClass.LP_FLAG, "1");
        secret=getIntent().getBooleanExtra("secret",false);
        //禁止截屏
        if ("0".equals(lpFlag)) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
        }
    }

    @Override
    public void initData() {
        initState();
        NavigationTools.saveUseRecord(this, "1", "03");
        MyApp.docunmentOpen = true;
        title = findViewById(R.id.title);
        iv_DataBaseBack = findViewById(R.id.iv_DataBaseBack);
        tvTiltle = findViewById(R.id.tvTiltle);
        pdf_rl = findViewById(R.id.pdf_rl);
        rlCircle = findViewById(R.id.rlCircle);
        progress_bar = findViewById(R.id.progress_bar);
        tvCompleteNum = findViewById(R.id.tvCompleteNum);
        tvComplete = findViewById(R.id.tvComplete);
        common_right_iv_ll = findViewById(R.id.common_right_iv_ll);
        common_collect_ll = findViewById(R.id.common_collect_ll);
        ivCollect = findViewById(R.id.ivCollect);
        webView = findViewById(R.id.webView);
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageFinished(WebView webView, String s) {
                super.onPageFinished(webView, s);
                try {
                    dismissLoading();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
        common_collect_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCollect) {
                    collectDocunment("0");
                    isCollect = false;
                    ivCollect.setBackgroundResource(R.drawable.icon_collect_48);
                } else {
                    collectDocunment("1");
                    isCollect = true;
                    ivCollect.setBackgroundResource(R.drawable.icon_yellow_collect);
                }
            }
        });
        iv_DataBaseBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (pdf_rl != null) {
                    pdf_rl.removeAllViews();
                }
                addPlayCount(allTime);
                finish();
            }
        });

        rlCircle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (timeEnd == -1) {
                    MyToast.show("还未达到学习任务规定时长");
                } else if (timeEnd == 0) {
                    addTaskCount();
                } else {
                    MyToast.show("您已经完成此学习任务");
                }
            }
        });
        // 可以自定义水印文字颜色、大小和旋转角度
        NavigationTools.setWaterMark(this, "6");
        fileName = getIntent().getStringExtra("fileName");
        dataCode = getIntent().getStringExtra("dataCode");
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", dataCode);
        EventBus.getDefault().post(new MyEvent(map));
        showLoading();
        fileAllUrl = getFilesDir() + File.separator + Urls.DOWNLOADCache + File.separator + fileName;
//        fileAllUrl = "/storage/emulated/0/QQBrowser/文档/登封市2022年教师招聘岗位一览表.pdf";
        KLog.i(fileName+"=="+fileAllUrl);
        tvTiltle.setText(fileName);
        if (!MyApp.mIsInitTBSSuccess) {
            pdf_rl.removeAllViews();
            pdf_rl.setVisibility(View.GONE);
            webView.setVisibility(View.VISIBLE);
            //用 PDFView 加载
            FileUtilss.deleteSingleFile(fileAllUrl);
            MyApp.downloadFiles.remove(fileName);
            openFile = false;
            openWeb();
        } else {
            registerBoradcastReceiver();
            new Thread() {
                @Override
                public void run() {
                    AESEncrypt.decryptFile(DocumentPreviewActivity.this, fileName, "DocumentPreviewActivity_OpenFile");
                }
            }.start();

        }
        readNum(dataCode);
        dialogList.add("分享");
        dialogList.add("在电脑上查看");
        dialogList.add("加入学习任务");
        dialogList.add("使用浏览器打开");
        dialogList.add("详细信息");
        dialogList.add("取消");
        common_right_iv_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomListsDialog = new BottomListsDialog(DocumentPreviewActivity.this, dialogList, new SelectDialogListener() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onListItemClick(int position, List<String> list) {
                        if (position == 0) {
                            if (docunmentEntity == null) {
                                bottomListsDialog.dismiss();
                                return;
                            }
                            Intent intent = new Intent(DocumentPreviewActivity.this, ShareActivity.class);
                            intent.putExtra("title", docunmentEntity.getDataTitle());
                            intent.putExtra("content", docunmentEntity.getKeyWord());
                            intent.putExtra("createEmployeeName", docunmentEntity.getUploadPersonName());
                            intent.putExtra("resourceId", dataCode);
                            intent.putExtra("size", Utils.changeKM(docunmentEntity.getDataSize()));
                            intent.putExtra("resourceType", 1);
                            startActivity(intent);
                        } else if (position == 1) {
                            new ForScreenInitDialog(DocumentPreviewActivity.this, new ShareDialogListener() {
                                @Override
                                public void onClick() {
                                    saveScan();
                                }
                            }).show();
                        } else if (position == 2) {
                            if (docunmentEntity == null) {
                                bottomListsDialog.dismiss();
                                return;
                            }
                            Intent intent = new Intent(DocumentPreviewActivity.this, StudyPlanAddActivity.class);
                            intent.putExtra("resourceId", dataCode);
                            intent.putExtra("describe", docunmentEntity.getKeyWord());
                            intent.putExtra("resourceType", 5);
                            intent.putExtra("title", docunmentEntity.getDataTitle());
                            intent.putExtra("content", docunmentEntity.getDataTitle());
                            intent.putExtra("size", Utils.changeKM(docunmentEntity.getDataSize()));
                            startActivity(intent);
                        } else if (position == 3) {
                            //浏览器去打开
                            openFile = false;
                            openWeb();
                        } else if (position == 4) {
                            //详细信息
                            Intent intent = new Intent(DocumentPreviewActivity.this, DocumentDetailActivity.class);
                            intent.putExtra("dataCode", dataCode);
                            startActivity(intent);
                        }
                        bottomListsDialog.dismiss();
                    }
                });
                bottomListsDialog.show();
            }
        });
        if(secret){
            common_collect_ll.setVisibility(View.GONE);
            common_right_iv_ll.setVisibility(View.GONE);
        }
        getData();
    }
    private void openFile(String filePath, String fileExt) {
        //设置回调
        ITbsReaderCallback callback = new ITbsReaderCallback() {
            @Override
            public void onCallBackAction(Integer actionType, Object args, Object result) {
                if (args instanceof Bundle) {
                    int id = ((Bundle) args).getInt("typeId");
                    if (ITbsReader.TBS_READER_TYPE_STATUS_UI_SHUTDOWN == id) {
                        finish();       // 加密文档弹框取消需关闭activity
                    }
                }
            }
        };
        KLog.i(filePath+"=="+fileExt);
        Bundle param = new Bundle();
        param.putString("filePath", filePath);
        param.putString("fileExt", fileExt); // 文件后缀名，如文件名为test.pdf，则只需要传入"pdf"
        param.putString("tempPath", getExternalFilesDir("temp").getAbsolutePath());
        //调用openFileReader打开文件
        openStatus=true;
        pdf_rl.post(new Runnable() {
            @Override
            public void run() {
                int height = pdf_rl.getHeight();
                param.putInt("set_content_view_height", height); // 文档内容的显示区域高度，自定义layout模式必须传入这个值
                try {
                    int ret = TbsFileInterfaceImpl.getInstance().openFileReader(
                            DocumentPreviewActivity.this, param, callback, pdf_rl);
                } catch (Exception e) {
                    e.printStackTrace();
                    openWeb();
                }
            }
        });
    }
    private void openWeb() {
        pdf_rl.removeAllViews();
        pdf_rl.setVisibility(View.GONE);
        webView.setVisibility(View.VISIBLE);
        String url = "";
        if (docunmentEntity != null) {
            if (!openFile) {
                openFile = true;
                url = docunmentEntity.getDataUrl();
                showLoading();
                try {
                    webView.loadUrl("https://web.chookss.com/doc/onlinePreview?url=" + Base64Utils.encode(url));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void saveScan() {
        Map<String, String> map = new HashMap<>();
        map.put("resourceId", dataCode);
        map.put("resourceType", "1");
        MyHttpRequest.getDefault().getRequestCompat(null, Urls.saveScan, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                JSONObject reObject = null;
                try {
                    reObject = new JSONObject(data);
                    if ("200".equals(reObject.getString("code"))) {
                    } else {
                        MyToast.show(reObject.getString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(errorMsg);
            }
        });
    }

    private void collectDocunment(String type) {
        Map<String, String> map = new HashMap<>();
        map.put("collectId", dataCode);
        map.put("collectStatus", type);
        map.put("collectType", "3"); // 3:资料库 4：图库 5：图文
        MyHttpRequest.getDefault().postRequest(new TypeToken<LzyResponse<String>>() {
        }.getType(), null, Urls.toCollect, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) {
                if (type.equals("0")) {
                    MyToast.show("取消收藏");
                } else {
                    MyToast.show("收藏成功");
                }
                EventBus.getDefault().post(new MyEvent("documentRefresh"));
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private String parseFormat(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1);
    }

    private void getData() {
        Map<String, String> allmap = new HashMap<>();
        allmap.put("dataCode", dataCode);
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<DocunmentEntity>>() {
        }.getType(), null, Urls.getDetail, SignUtils2.makeSignStr(allmap), false, new ObserverCallback<DocunmentEntity>() {
            @Override
            public void onSuccess(DocunmentEntity data) {
                if (data != null) {
                    dismissLoading();
                    docunmentEntity = data;
                    if (data.getIsCollect().equals("1")) {
                        isCollect = true;
                        ivCollect.setBackgroundResource(R.drawable.icon_yellow_collect);
                    } else {
                        isCollect = false;
                        ivCollect.setBackgroundResource(R.drawable.icon_collect_48);
                    }
                    if (!MyApp.mIsInitTBSSuccess) {
                        try {
                            webView.loadUrl("https://web.chookss.com/doc/onlinePreview?url=" + Base64Utils.encode(data.getDataUrl()));
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (!openFile) {
                        //先加载失败，接口还没返回数据
                        openWeb();
                    }
                }
            }

            @Override
            public void onError(String errorMsg) {
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void readNum(String dataCode) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", dataCode);
        MyHttpRequest.getRequest(Urls.getUrlByCode, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        JSONObject jsonObject1 = jsonObject.getJSONObject("data");
                        compeleteFlag = jsonObject1.getString("compeleteFlag");
                        if (!Utils.isNull(compeleteFlag)) {
                            rlCircle.setVisibility(View.VISIBLE);
                            if ("1".equals(compeleteFlag)) {
                                timeEnd = 1;
                                progress_bar.setVisibility(View.GONE);
                                tvCompleteNum.setVisibility(View.GONE);
                                tvComplete.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                                tvComplete.setText("已学完");
                            } else {
                                progress_bar.setVisibility(View.VISIBLE);
                                tvCompleteNum.setVisibility(View.VISIBLE);
                                tvCompleteNum.setText("60s");
                                tvComplete.setText("后完成学习");
                                progress_bar.setDuration(61000);
                                progress_bar.start();
                                startTimer();
                            }

                        }
                    }else {
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }
                } catch (
                        JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }


    @Override
    public void onBackPressed() {
        if (pdf_rl != null) {
            pdf_rl.removeAllViews();
        }
        addPlayCount(allTime);
        super.onBackPressed();
    }

    private void startTimer() {
        if (mTimer == null) {
            mTimer = new Timer();
        }
        if (mTimerTask == null) {
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //每分中上传数据
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
        }
        if (mTimer != null && mTimerTask != null) {
            mTimer.schedule(mTimerTask, 1000, 1000);//执行定时器中的任务
        }
    }

    private int allTime = 0;
    // handler类接收数据
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 1) {
                allTime++;
                KLog.i((allTime * 100) / 60 + "===" + allTime);
                if (allTime == 60) {
                    timeEnd = 0;
                    progress_bar.setVisibility(View.GONE);
                    tvCompleteNum.setVisibility(View.VISIBLE);
                    tvCompleteNum.setText("点击");
                    tvComplete.setText("学习任务已完成");
                    stopTimer();
                } else {
                    if (timeEnd != 0) {
                        tvCompleteNum.setText((60 - allTime) + "s");
                        tvComplete.setText("后完成学习");
                    }
                }
            }
        }

    };

    /**
     * 增加播放时长
     */
    private void addPlayCount(int seconds) {
        Map<String, String> map = new HashMap<>();
        map.put("dataCode", dataCode);
        map.put("readTime", seconds + "");
        MyHttpRequest.getDefault().postRequestCompat(null, Urls.addReadCount, SignUtils2.makeSignStr(map), false, new ObserverCallback<String>() {
            @Override
            public void onSuccess(String data) throws Exception {

            }

            @Override
            public void onError(String errorMsg) {
            }
        });
    }

    /**
     * 完成学习任务
     */
    private void addTaskCount() {
        Map<String, String> map = new HashMap<>();
        map.put("videoId", dataCode);
        map.put("type", "3");
        MyHttpRequest.postRequest(Urls.addTaskCount, this, SignUtils2.makeSignStr(map), new JsonCallback<String>() {
            @Override
            public void onSuccess(Response<String> response) {
                try {
                    JSONObject jsonObject = new JSONObject(response.body().toString());
                    if ("200".equals(jsonObject.getString("code"))) {
                        timeEnd = 1;
                        MyToast.show("完成学习任务");
                        tvComplete.setTextSize(TypedValue.COMPLEX_UNIT_SP, 15);
                        tvComplete.setText("已学完");
                    } else {
                        timeEnd = 0;
                        if (jsonObject.getString("code").startsWith("400")) {
                            OkGoUtil.onErrorIntent(jsonObject.getString("code"),jsonObject.getString("msg"));
                        }else{
                            MyToast.show(jsonObject.getString("msg"));
                        }
                    }

                } catch (
                        JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    private void registerBoradcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction("DocumentPreviewActivity_OpenFile");// 获取数据
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                dismissLoading();
                boolean decryptStatus = intent.getBooleanExtra("decryptStatus", false);
                if (decryptStatus) {
                    openFile(fileAllUrl, parseFormat(fileAllUrl));
                } else {
                    pdf_rl.removeAllViews();
                    pdf_rl.setVisibility(View.GONE);
                    webView.setVisibility(View.VISIBLE);
                    //用 PDFView 加载
                    FileUtilss.deleteSingleFile(fileAllUrl);
                    MyApp.downloadFiles.remove(fileName);
                    openFile = false;
                    openWeb();
                }
            }
        }

    };

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getMap() != null) {
            Map<String, String> map = messageEvent.getMap();

        } else {
            String msg = messageEvent.getMessage();
            if (Utils.isNull(msg)) {
                return;
            }
            if (msg.equals("Web_Close")) {
                finish();
            } else if (msg.equals("Web_Cancel_dialog")) {
                dismissLoading();
            }
        }
    }
    // 销毁资源使用onpause + ondestroy的方式。避免onDestroy延迟回调
    private void destroy() {
        if (isDestroyed) {
            return;
        }
        // 回收资源
        pdf_rl.removeAllViews(); //移除内容显示区域layout
        try {
            if(openStatus){
                TbsFileInterfaceImpl.getInstance().closeFileReader(); //关闭fileReader
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        isDestroyed = true;
    }


    @Override
    protected void onPause() {
        super.onPause();
        if (isFinishing()) {
            destroy();
        }
    }

    //横屏切换
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        DisplayMetrics dm = new DisplayMetrics();
        ((Activity) this).getWindowManager().getDefaultDisplay().getMetrics(dm);
        int w = dm.widthPixels;
        int h = dm.heightPixels - title.getHeight();
        TbsFileInterfaceImpl.getInstance().onSizeChanged(w, h);
    }

    @Override
    protected void onDestroy() {
        MyApp.docunmentOpen = false;
        destroy();
        stopTimer();
        FileUtilss.deleteDir2(new File(getFilesDir() + "/TbsReaderTemp"));
        FileUtilss.deleteDir2(new File(getFilesDir() + File.separator + Urls.DOWNLOADCache));
        super.onDestroy();
    }

    /**
     * 停止定时器，初始化定时器开关
     */
    private void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
            mTimerTask = null;
        }
    }
}
